<template>
	<div class="zy-content">
		<back-level></back-level>
		<div class="search-box-layout">
			<!-- <div class="btns clear"> -->
			<span class="title">{{ type == 'edit' ? '编辑' : '新增' }}</span>
			<Form class="mt16" ref="formDynamic" v-bind="$attrs" v-on="$listeners" :model="formItem">
				<Row :gutter="24">
					<div v-for="(item, index) in columns" :key="index">
						<Col :span="item.span || span">
							<div class="ipt">
								<FormItem
									:prop="item.key"
									:label="item.title"
									:rules="{
										type: item.dataType || 'string',
										required: item.required || false,
										message: item.message || `请${item.type ? '选择' : '输入'}${item.title}`,
										trigger: item.trigger || 'blur,change',
									}"
								>
									<Select
										:disabled="checkDisableStatus(item)"
										v-model="formItem[item.key]"
										filterable
										v-if="item.type == 'select'"
										:placeholder="item.placeholder || '请选择' + item.title"
										clearable
										:multiple="!!item.multiple"
									>
										<Option
											v-for="(itemS, indexS) of item.dicData ? item.dicData : allDicData[item.key + 'List']"
											:value="itemS[!!item.params ? item.params.value : 'value']"
											:key="indexS"
											:label="itemS[!!item.params ? item.params.label : 'label']"
										>
										</Option>
									</Select>
									<Select
										:disabled="checkDisableStatus(item)"
										v-else-if="item.type == 'search'"
										v-model="formItem[item.key]"
										filterable
										clearable
										:remote-method="fn['get' + item.key]"
										:placeholder="item.placeholder || '请选择' + item.title"
									>
										<Option
											v-for="(itemS, indexS) of item.dicData ? item.dicData : allDicData[item.key + 'List']"
											:value="itemS[!!item.params ? item.params.value : 'value']"
											:key="indexS"
											:label="itemS[!!item.params ? item.params.label : 'label']"
										>
										</Option>
									</Select>
									<Cascader
										:disabled="checkDisableStatus(item)"
										v-else-if="item.type == 'cascader'"
										clearable
										:data="item.dicData ? item.dicData : allDicData[item.key + 'List']"
										v-model="formItem[item.key]"
										change-on-select
										:placeholder="item.placeholder || '请选择' + item.title"
									>
									</Cascader>
									<DatePicker
										v-else-if="
											item.type == 'date' || item.type == 'daterange' || item.type == 'month' || item.type == 'datetimerange' || item.type == 'year'
										"
										:disabled="checkDisableStatus(item)"
										:value="formItem[item.key]"
										@on-change="timeChange($event, item.key)"
										:type="item.type"
										:format="item.format ? item.format : 'yyyy-MM-dd'"
										:placeholder="item.placeholder || '请选择日期'"
									/>

									<RadioGroup v-else-if="item.type == 'radio'" :disabled="checkDisableStatus(item)" v-model="formItem[item.key]">
										<Radio label="">{{ $t('common.all') }}</Radio>
										<Radio label="1">{{ $t('common.Yes') }}</Radio>
										<Radio label="0">{{ $t('common.No') }}</Radio>
									</RadioGroup>
									<uploadFile
										v-else-if="item.type == 'upload'"
										:fileList="formItem[item.key]"
										:disabled="checkDisableStatus(item)"
										:accept="item.accept || ',*'"
										:type="item.showType"
										@change="
											(list) => {
												formItem[item.key] = list;
											}
										"
									></uploadFile>
									<Input
										v-else
										type="text"
										clearable
										:disabled="checkDisableStatus(item)"
										v-model="formItem[item.key]"
										:placeholder="item.placeholder || '请输入' + item.title"
										class="inputBorder"
										:maxlength="item.maxlength || 200"
									></Input>
								</FormItem>
							</div>
						</Col>
					</div>
					<div></div>
				</Row>
				<!-- <FormItem>
					<Button type="primary" @click="handleSave('formDynamic')">Submit</Button>
					<Button @click="handleReset('formDynamic')" style="margin-left: 8px">Reset</Button>
				</FormItem> -->
			</Form>

			<bottom-handle-wrap>
				<!-- <FormItem> -->
				<Button @click="$router.go(-1)">{{ $t('preliminary.Cancel') }}</Button>
				<Button style="margin-right: 10px" type="primary" :loading="loading" @click="handleSave">
					{{ $t('maintenance.Confirmed') }}
				</Button>
				<!-- </FormItem> -->
			</bottom-handle-wrap>
		</div>
	</div>
</template>

<script>
import uploadFile from './modules/uploadFile';
import recursion from '@/util/recursion';
import toggleTableOperation from '@/mixins/toggleTableOperation';
export default {
	name: 'equipmentsLedgerPageList',
	components: { uploadFile },
	mixins: [toggleTableOperation],
	props: {
		columns: {
			type: Array,
		},
		span: {
			type: Number,
			default: 8,
		},
		otherSpan: {
			type: Number,
			default: 4,
		},
		formData: {
			type: {},
		},
	},
	computed: {
		type() {
			if (this.formData && this.formData.id) {
				return 'edit';
			} else {
				return 'add';
			}
		},
	},
	data() {
		return {
			formItem: {},
			fn: {},
			allDicData: {},
			loading: false,
		};
	},
	watch: {
		formData: {
			handler() {
				this.$set(this, 'formItem', this.formData);
			},
			deep: true,
		},
	},
	created() {
		this.columnsInit();
		// this.$nextTick(()=>{
		// })
		// this.getFaultCategory("设备类型");
	},
	methods: {
		checkDisableStatus(item) {
			const disabled = this.type == 'edit' ? item.editDisabled || false : item.addDisabled || false;
			return disabled;
		},
		handleSave() {
			this.$refs['formDynamic'].validate((valid) => {
				if (valid) {
					this.loading = true;
					if (this.type == 'add') {
						this.$emit('handleSave', this.formItem, () => {
							this.loading = false;
						});
					} else {
						this.$emit('handleUpdata', this.formItem, () => {
							this.loading = false;
						});
					}
				} else {
					this.$Message.error('请检查数据');
				}
			});
		},
		columnsInit() {
			this.columns.forEach((res) => {
				const item = res;
				if (item.dicUrl) {
					this[item.key] = [];
					if (item.type == 'select') {
						this.getDicData(item.dicUrl, item.key);
					} else if (item.type == 'cascader') {
						this.getCasDicData(item.dicUrl, item.key, item.params);
					}
				}
				if (item.type == 'search') {
					const that = this;
					this.fn['get' + item.key] = function (query) {
						let params,
							data = {};
						if (item.queryMethod == 'post') {
							data = {
								...item.queryParams,
							};
							data[item.queryName] = query;
						} else {
							params = {
								...item.queryParams,
							};
							params[item.queryName] = query;
						}
						that
							.axios({
								method: item.queryMethod || 'get',
								url: item.dicUrl,
								params,
								data,
							})
							.then((re) => {
								if (re.code === 200) {
									const resStr = that.getData(item.resultParams, re) || [];
									that.$set(that.allDicData, `${item.key}List`, item.resultParams ? resStr : re.data);
								}
							});
					};
				}
				this.initDefaultValue(item);
			});
		},
		initDefaultValue(item) {
			if (item.type == 'date' || item.type == 'daterange' || item.type == 'month' || item.type == 'datetimerange' || item.type == 'year') {
				this.initDefaultTimeParams(item);
			} else if (item.defaultValue) {
				this.$set(this.formItem, item.key, item.defaultValue);
			}
		},
		initDefaultTimeParams(item) {
			if (item.defaultTimeRange) {
				const valueFormatter = item.format ? item.format.replace(/y/g, 'Y').replace(/d/g, 'D') : 'YYYY-MM-DD';
				const defaultTimeRangeList = [
					this.$moment(new Date()).subtract(item.defaultTimeRange, 'days').format(valueFormatter),
					this.$moment(new Date()).format(valueFormatter),
				];
				// this.$set(this.columns[index], 'defaultTimeRangeList', defaultTimeRangeList);
				this.$set(this.formItem, item.key, defaultTimeRangeList);
			}
		},
		timeChange(val, key) {
			if (Array.isArray(val) && !val[0]) {
				delete this.formItem[key];
			} else this.$set(this.formItem, key, val);

			const arg = this.columns.find((item) => item.key == key);
			if (arg && arg.cascader) {
				const obj = JSON.stringify({ eqfaeqr: val }).replace('eqfaeqr', `${key}`);
				this.$set(this.cascaderParams, `${arg.cascader}CascaderParams`, JSON.parse(obj));
				const arg1 = this.columns.find((item) => item.key == arg.cascader);
				this.getDicData(arg1.dicUrl, arg1.key);
			}
		},
		getData(str, apiData) {
			const resultArray = str.split('.');
			let res = JSON.parse(JSON.stringify(apiData));
			resultArray.forEach((item, index) => {
				if (index !== 0 && item !== 'res') {
					res = res[item];
				}
			});
			return res;
		},
		getDicData(url, key) {
			this.$nextTick(() => {
				this.axios({
					method: 'get',
					url: url,
				}).then((res) => {
					this.$set(this.allDicData, `${key}List`, res.data);
				});
			});
		},
		getCasDicData(url, key, params) {
			this.$nextTick(() => {
				this.axios({
					method: 'get',
					url: url,
				}).then((res) => {
					let obj = {};
					if (params) {
						obj = params;
					} else {
						obj = {
							label: 'name',
							value: 'code',
							children: 'children',
						};
					}
					this.$set(this.allDicData, `${key}List`, recursion.convertTree(res.data, obj));
				});
			});
		},
		reset() {
			let obj = { ...this.formItem };

			this.columns.forEach((item) => {
				if (item.noreset == true) {
					this.initDefaultTimeParams(item);
				} else delete obj[item.key];
			});
			this.$set(this, 'formItem', obj);

			this.$emit('reset');
			this.changeNum();
		},
		//分页
		changeNum() {
			this.$emit('getSearch', this.formItem);
		},
	},
};
</script>
<style scoped lang="scss">
.title {
	font-size: 16px;
	margin-left: 10px;
}
</style>
